<template>
    <el-row :gutter="20">
        <el-col :sm="24" :md="12" :lg="6">
            <div class="card" :class="{ 'card-selected': examType === 1 }" @click="examClick(1)">
                <div class="card-header">
                    <h2>今日浏览量概况（PA）</h2>
                </div>
                <div class="data-container">
                    <div class="main-value">
                        {{
                            props.trafficOverview[1].aoList[props.trafficOverview[1].aoList.length - 1].data
                        }}
                    </div>
                </div>
                <div class="comparison-container">
                    <div class="comparison-item">
                        <div class="comparison-title">昨日：</div>
                        <div class="comparison-value neutral">{{ props.trafficOverview[1].yesterdayData }}</div>
                    </div>
                    <div class="comparison-item">
                        <div class="comparison-title">近7日：</div>
                        <div class="comparison-value neutral">{{ props.trafficOverview[1].last7DaysTotal }}</div>
                    </div>
                    <div class="comparison-item">
                        <div class="comparison-title">近30日：</div>
                        <div class="comparison-value neutral">{{ props.trafficOverview[1].last30DaysTotal }}</div>
                    </div>
                </div>
            </div>
            <div class="card marT30" :class="{ 'card-selected': examType === 2 }" @click="examClick(2)">
                <div class="card-header">
                    <h2>今日访客数概况</h2>
                </div>
                <div class="data-container">
                    <div class="main-value">
                        {{
                            props.trafficOverview[0].aoList[props.trafficOverview[0].aoList.length - 1].data
                        }}
                    </div>
                </div>
                <div class="comparison-container">
                    <div class="comparison-item">
                        <div class="comparison-title">昨日：</div>
                        <div class="comparison-value neutral">{{ props.trafficOverview[0].yesterdayData }}</div>
                    </div>
                    <div class="comparison-item">
                        <div class="comparison-title">近7日：</div>
                        <div class="comparison-value neutral">{{ props.trafficOverview[0].last7DaysTotal }}</div>
                    </div>
                    <div class="comparison-item">
                        <div class="comparison-title">近30日：</div>
                        <div class="comparison-value neutral">{{ props.trafficOverview[0].last30DaysTotal }}</div>
                    </div>
                </div>
            </div>
        </el-col>
        <el-col :sm="24" :md="12" :lg="18">
            <div class="card-header">
                <h2>{{ examType === 1 ? '浏览量趋势' : '访客量趋势' }}</h2>
            </div>
            <div class="chart" ref="chartRef"></div>
        </el-col>
    </el-row>
</template>
<script lang="ts" setup>
import * as echarts from 'echarts'
import { hexToRgba, getCssVar } from '@/utils/ui'
import { EChartsOption } from 'echarts'
import { useChart } from '@/composables/useChart'
import { onMounted, watch, nextTick, ref, computed } from 'vue'

const props = defineProps({
    trafficOverview: {
        type: Array<any>,
        default: () => []
    }
})

const examType = ref(1)

const {
    chartRef,
    isDark,
    getAxisLabelStyle,
    getAxisLineStyle,
    getAxisTickStyle,
    getSplitLineStyle
} = useChart()

// 真实数据
const realData = computed(() => {
    if (examType.value === 1) {
        return props.trafficOverview[1].aoList.map((e: any) => e.data)
    } else {
        return props.trafficOverview[0].aoList.map((e: any) => e.data)
    }
})

const xAxisData = computed(() => {
    if (examType.value === 1) {
        return props.trafficOverview[1].aoList.map((e: any) => e.statDate.slice(5, 10))
    } else {
        return props.trafficOverview[0].aoList.map((e: any) => e.statDate.slice(5, 10))
    }
})

// 图表初始化
let chartInstance: echarts.ECharts | null = null

function renderChart(isInit = false) {
    if (!chartRef.value) return
    if (!chartInstance) {
        chartInstance = echarts.init(chartRef.value as HTMLElement)
    }
    const option: EChartsOption = {
        animation: true,
        animationDuration: isInit ? 0 : 1500,
        animationDurationUpdate: isInit ? 0 : 1500,
        grid: {
            left: '2.2%',
            right: '3%',
            bottom: '0%',
            top: '10px',
            containLabel: true
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xAxisData.value,
            axisTick: getAxisTickStyle(),
            axisLabel: getAxisLabelStyle(true),
            axisLine: getAxisLineStyle(true)
        },
        yAxis: {
            type: 'value',
            min: 0,
            max: Math.max(...realData.value),
            axisLabel: getAxisLabelStyle(true),
            axisLine: getAxisLineStyle(!isDark.value),
            splitLine: getSplitLineStyle(true)
        },
        series: [
            {
                name: examType.value === 1 ? '浏览量' : '访客数',
                color: getCssVar('--main-color'),
                type: 'line',
                data: isInit ? new Array(24).fill(0) : realData.value,
                smooth: false, // 关闭平滑，标准折线
                symbol: 'circle',
                symbolSize: 8,
                lineStyle: {
                    width: 2.2
                },
                itemStyle: {
                    color: getCssVar('--main-color'),
                    borderWidth: 2,
                    borderColor: '#fff'
                },
                animationDuration: isInit ? 0 : 1500,
                animationDurationUpdate: isInit ? 0 : 1500
            }
        ]
    }
    chartInstance.setOption(option, true)
    chartInstance.resize()
}

function tryRenderChart(isInit = false) {
    nextTick(() => {
        const el = chartRef.value as HTMLElement
        if (el && el.clientWidth > 0 && el.clientHeight > 0) {
            renderChart(isInit)
        } else {
            setTimeout(() => renderChart(isInit), 300)
        }
    })
}
const examClick = (e: number) => {
    examType.value = e
}

// 切换类型或外部数据变化时，重新渲染图表
watch(examType, () => {
    tryRenderChart(false)
})

watch(() => props.trafficOverview, () => {
    tryRenderChart(false)
}, { deep: true })

onMounted(() => {
    tryRenderChart(true)
    setTimeout(() => tryRenderChart(false), 100)
    window.addEventListener('resize', () => {
        if (chartInstance) chartInstance.resize()
    })
})

watch(isDark, () => {
    tryRenderChart()
})

watch(examType, () => {
    tryRenderChart()
})
</script>
<style lang="scss" scoped>
.card {
    background: #f7f8fa !important;
    border-radius: 16px;
    padding: 30px;
    /* 预留边框空间，防止有无边框切换时抖动 */
    box-sizing: border-box;
    border: 2px solid transparent;
    transition: border-color 0.2s;
}

.card-selected {
    border-color: var(--el-color-primary, #409EFF);
}

.card-header {
    display: flex;
    align-items: center;
    margin-bottom: 25px;
    color: #2c3e50;
}

.card-header h2 {
    font-weight: 600;
    font-size: 20px;
}

.data-container {
    margin-bottom: 25px;
}

.main-value {
    font-size: 48px;
    font-weight: 700;
    color: #333;
    margin-bottom: 15px;
}

.comparison-container {
    display: flex;
    padding-top: 20px;
}

.comparison-item {
    display: flex;
    text-align: center;
    padding-right: 15px;
}

.comparison-title {
    font-size: 14px;
    color: #7f8c8d;
    margin-bottom: 8px;
}

.comparison-value {
    font-size: 18px;
    font-weight: 600;
}

.neutral {
    color: #7f8c8d;
}

.marT30 {
    margin-top: 30px;
}

.chart {
    width: 100%;
    height: calc(100% - 30px);
}
</style>